package com.eventur;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class DisplayActivity extends Activity implements LocationListener{
	String title = null;
	String time = null;
	String venue= null;
	String description = null;
	String type = null;
	String organization = null;
	private static double currentLatitude = 0.0;
	private static double currentLongitude = 0.0;
	private static final int MENU_HOME = Menu.FIRST;

	private static final int MENU_QUIT = Menu.FIRST+1;

	private LocationManager locationManager;
	private Location location = null;



	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume(){
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// Add two example menu buttons
		menu.add(0,MENU_HOME,0,"Home");
		//menu.add(0,MENU_QUIT,1,"Quit");
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()	){
		case MENU_HOME: Intent intent = new Intent(this, HomeActivity.class);;
		startActivity(intent);finish();
		return true;
		/*case MENU_QUIT: int pid = android.os.Process.myPid();
		System.out.println("Process id:"+pid);
		android.os.Process.killProcess(pid); 
		return true;*/

		}
		return false;

	}



	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detailed);
		TextView titleText = (TextView) findViewById(R.id.titleText);
		TextView timeText = (TextView) findViewById(R.id.timeText);
		TextView venueText = (TextView) findViewById(R.id.venueText);
		TextView descriptionText = (TextView) findViewById(R.id.descriptionText);
		ImageView imageView = (ImageView) findViewById(R.id.imageView);
		Button mapButton = (Button) findViewById(R.id.mapButton);
		Button browseButton = (Button) findViewById(R.id.browseButton);
		//TextView visitWebText = (TextView) findViewById(R.id.visitWebsite);
		TextView typeText = (TextView)findViewById(R.id.typeText);
		TextView orgText = (TextView) findViewById(R.id.organizationText);
		Bundle bundle = getIntent().getExtras();
		String eventTitle = null;
		if (bundle != null) {
			eventTitle = bundle.getString("eventTitle");
			currentLatitude = bundle.getDouble("currentLatitude");
			currentLongitude = bundle.getDouble("currentLongitude");
			System.out.println("opened display activity:clat and clon:"+currentLatitude+currentLongitude+eventTitle);

		}

		Event event = new Event();
		ListEvents listEvent = new ListEvents();
		event = listEvent.getEvent(eventTitle);
		//visitWebText.setText("Please visit the website for a better view");
		title = event.getTitle();
		venue = event.getVenue();
		type = event.getType();
		organization = event.getOrganization();
		/*if(organization.length()>36){
			//organization = new StringBuffer(organization).insert(36,"\n").toString();
			//orgText.setHeight(2*orgText.getHeight());
			orgText.setTextSize("6px");
			System.out.println("height:"+orgText.getHeight());
		}*/
		//orgText.setSelected(true);
		//orgText.setEllipsize(TruncateAt.MARQUEE);  
		orgText.setText(organization);
		typeText.setText(type);
		titleText.setText(title);
		timeText.setText(event.getsDate());
		if(event.getDistance() !=0.0){
			venueText.setText(venue + " is  " + Double.toString(event.getDistance())+ " miles away");
		}
		else 
			venueText.setText(venue);
		final String linkToEvent = event.getLink();
		descriptionText.setText(event.getDescription());
		//final String venueAddress = event.getVenueAddress();
		final double latitude = event.getLatitude();
		final double longitude = event.getLongitude();
		browseButton.setOnClickListener( new View.OnClickListener()
		{
			public void onClick(View v)
			{
				setContentView(R.layout.webview);
				WebView wv = (WebView)findViewById( R.id.webviewscreen );
				wv.loadUrl(linkToEvent);
			}
		});

		mapButton.setOnClickListener( new View.OnClickListener()
		{
			public void onClick(View v)
			{
				final Intent intent = new Intent(DisplayActivity.this, MapViewActivity.class);
				final Bundle bundle = new Bundle();
				bundle.putString("key", "single");
				bundle.putDouble("latitude",latitude);
				bundle.putDouble("longitude",longitude);
				System.out.println("placing the current lat lon in bundle dispact:"+currentLatitude+currentLongitude);
				bundle.putString("title", title);
				bundle.putString("venue", venue);
				System.out.println("MapViewActivity required");

				if(currentLatitude==0.0 && currentLongitude==0.0){
					AlertDialog alertDialog = new AlertDialog.Builder(DisplayActivity.this).create();
					alertDialog.setTitle("Map");
					alertDialog.setIcon(R.drawable.gpsandroid);
					alertDialog.setMessage("Allow device to fetch your current Location?");
					//alertDialog.setIcon(R.drawable.search);
					alertDialog.setButton("Fetch", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							fetchUserLocation();
							bundle.putDouble("currentLatitude",currentLatitude);
							bundle.putDouble("currentLongitude",currentLongitude);
							intent.putExtras(bundle);
							startActivity(intent);
						}

					});
					alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							bundle.putDouble("currentLatitude",currentLatitude);
							bundle.putDouble("currentLongitude",currentLongitude);
							intent.putExtras(bundle);
							startActivity(intent);
							return;
						}}); 
					alertDialog.show();	
				}

				else{
					bundle.putDouble("currentLatitude",currentLatitude);
					bundle.putDouble("currentLongitude",currentLongitude);
					intent.putExtras(bundle);
					startActivity(intent);

				}
			}
		});
		LazyAdapter.imageLoader.DisplayImage(event.getImageLink(), DisplayActivity.this, imageView);
		
		 

		/*Bitmap bitmap;
		try {
			bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://a1.twimg.com/profile_images/1148249687/eventur_1_bigger.png").getContent());
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			bitmap = BitmapFactory.decodeFile("assets/heinz7.jpg");
			e1.printStackTrace();
		}
		try {
			try{
				bitmap = BitmapFactory.decodeStream((InputStream)new URL(event.getImageLink()).getContent());}
			catch(Exception e){
				bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://a1.twimg.com/profile_images/1148249687/eventur_1_bigger.png").getContent());
			}

			int width = 0;
			int height =0;
			int newWidth = 125;
			int newHeight = 125;

			try{
				width = bitmap.getWidth();
				height = bitmap.getHeight();
			}
			catch(Exception e){
				width = 65;
				height = 65;
			}
			float scaleWidth = ((float)newWidth)/width;
			float scaleHeight = ((float)newHeight)/height;
			Matrix mat = new Matrix();
			mat.postScale(scaleWidth, scaleHeight);

			try{
				System.out.println("Drawing image with height:"+height+" and width:"+width);

				Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,mat,true);
				BitmapDrawable bmd = new BitmapDrawable(newBitmap);
				imageView.setImageDrawable(bmd);
				System.out.println("Drawing image with height:"+newBitmap.getHeight()+" and width:"+newBitmap.getWidth());
				//imageView.setScaleType(ScaleType.CENTER);
			}
			catch(Exception e){

			}

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
*/
	}

	protected void fetchUserLocation() {
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
		location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		try {
			System.out.println("Fetching Location:");
			currentLatitude = location.getLatitude();
			currentLongitude = location.getLongitude();
			System.out.println("latitude/long obtained:"
					+ currentLatitude + ":" + currentLongitude);
		} catch (Exception e) {
			try {
				while (location.getLatitude() == 0.0
						|| location.getLongitude() == 0)
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER, 0, 0,
							this);

			} catch (Exception ex) {

			}
		}

		// interchanging values here
		currentLongitude = location.getLongitude();
		currentLatitude = location.getLatitude();


	}

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

}
